package com.hhs.storage.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hhs.storage.bean.*;
import com.hhs.storage.dao.BusinessOrderDao;
import com.hhs.storage.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hhs.storage.util.SysUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hhs
 * @since 2023-01-06
 */
@Service
@Transactional
public class BusinessOrderServiceImpl extends ServiceImpl<BusinessOrderDao, BusinessOrder> implements BusinessOrderService {
    @Resource
    private BusinessDocumentService businessDocumentService;
    @Resource
    private BaseRoleService roleService;
    @Resource
    private HttpServletRequest request;
    @Resource
    private ContractService contractService;
    @Resource
    private ComsumerService comsumerService;
    @Resource
    private CarFleetService carFleetService;
    @Resource
    private RegionService regionService;
    @Resource
    TypeDicService typeDicService;
    @Override
    public Map<String, Object> getAll(BusinessOrder businessOrder, InputParam inputParam) {
        QueryWrapper<BusinessOrder> ew=new QueryWrapper<>();

        if(!StringUtils.isEmpty(inputParam.getName())){
            //根据合同名称查询
            ew.inSql("business_document_id","select id from business_document where contract_id in(select id from contract where project like '%"+inputParam.getName()+"%' )");
        }
        if(!StringUtils.isEmpty(inputParam.getContractType())){
            //根据合同类型查询
            ew.inSql("business_document_id","select id from business_document where contract_id in(select id from contract where contract_type = '"+inputParam.getContractType()+"' )");
            ew.inSql("contract_id","select id from contract where contract_type = '"+inputParam.getContractType()+"'");
        }
        if(!StringUtils.isEmpty(businessOrder.getCarfleetId())){
            //根据车队查询
            ew.eq("carfleet_id",businessOrder.getCarfleetId());
        }
        if(businessOrder.getState()!=null){
            //根据状态查询
            ew.eq("state",businessOrder.getState());
        }
        ew.orderByDesc("create_time");
        Page<BusinessOrder> result = this.page(new Page<BusinessOrder>(
                inputParam.getPage(),
                inputParam.getSize()),ew);
        Map<String, Object> map = new HashMap<String, Object>();
        List<BusinessOrder> rows=result.getRecords();
        for (int i = 0; i < rows.size(); i++) {
            BusinessOrder temp=rows.get(i);
            //关联的订单信息
            BusinessDocument document=businessDocumentService.getById(temp.getBusinessDocumentId());
            temp.setBusinessDocument(document);
            if (document!=null){//订单本身的合同与客户信息
                Contract contract=contractService.getById(document.getContractId());
                document.setContract(contract);
                Comsumer comsumer=comsumerService.getById(document.getCustomerId());
                document.setComsumer(comsumer);
            }
            //车队信息
            CarFleet carFleet=carFleetService.getById(temp.getCarfleetId());
            temp.setCarFleet(carFleet);
            //特殊处理，原本的区域不使用，改成读取字典数据
//            Region startRegion=regionService.getById(temp.getStartPlace());
//            Region endRegion=regionService.getById(temp.getEndPlace());
            Region startRegion = typeDicService.formatRegion(temp.getStartPlace());
            Region endRegion = typeDicService.formatRegion(temp.getEndPlace());

            temp.setStartRegion(startRegion);
            temp.setEndRegion(endRegion);
        }
        map.put("rows", rows);
        map.put("total",result.getTotal());
        map.put("code", 1);
        return map;
    }

    @Override
    public Map<String, Object> add(BusinessOrder businessOrder, String dataJson) {
        //检查当前角色是否业务员
        boolean flag= roleService.hasRole(SysUtil.ROLE_FLAG_XDY,SysUtil.getLoginUserId(request));
        if (!flag){
            return ResponseInfo.error("只有下单员才可以下单");
        }
        //查看单据是否存在，并且是否待完成
        String businessDocumentId=businessOrder.getBusinessDocumentId();
        BusinessDocument document=businessDocumentService.getById(businessDocumentId);
        if (document==null){
            return ResponseInfo.error("单据不存在");
        }
        if (document.getState()!=BusinessDocument.STATUS_CREATE){
            return ResponseInfo.error("单据执行中或已完成");
        }
        //将json数据转换成容器对象
        List<Map<String,Object>> data= (List<Map<String, Object>>) JSON.parse(dataJson);
        BigDecimal total=new BigDecimal(0);
        for (int i = 0; i <data.size() ; i++) {
            total=total.add(new BigDecimal((String) data.get(i).get("num")));
        }
        if (total.compareTo(document.getNum())!=0){
            return ResponseInfo.error("单据分配数据错误");
        }
        for (int i = 0; i <data.size() ; i++) {
            Map<String,Object> temp=data.get(i);
            BusinessOrder order=new BusinessOrder();
            order.setId(SysUtil.UUID());
            order.setBusinessDocumentId(businessDocumentId);
            order.setCarfleetId((String) temp.get("carfleetId"));
            order.setNum(new BigDecimal((String) temp.get("num")));
            order.setLastNum(new BigDecimal((String) temp.get("num")));
            order.setState(BusinessOrder.STATUS_CREATE);//设置状态待完成
            order.setCreator(SysUtil.getLoginUserId(request));//设置完成人
            order.setCreateTime(LocalDateTime.now());
            order.setStartPlace((String) temp.get("startPlace"));
            order.setEndPlace((String) temp.get("endPlace"));
            order.setMidPlace((String) temp.get("midPlace"));
            this.save(order);
        }
        //更新单据为已下单
        document.setState(BusinessDocument.STATUS_ORDERED);
        businessDocumentService.updateById(document);
        return ResponseInfo.success();
    }

    @Override
    public Map<String, Object> changeOrderCarFleet(String id, String carFleetId) {
        BusinessOrder order =this.getById(id);
        if (order==null){
            return ResponseInfo.error("错误的参数");
        }
        UpdateWrapper<BusinessOrder> uw=new UpdateWrapper<>();
        uw.set("carfleet_id",carFleetId);
        uw.eq("id",id);
        this.update(uw);
        return ResponseInfo.success();
    }

    @Override
    public Map<String, Object> getByDocuId(InputParam inputParam) {
        QueryWrapper<BusinessOrder> ew=new QueryWrapper<>();

        if(StringUtils.isEmpty(inputParam.getMainId())){
            //根据合同名称查询
            return ResponseInfo.error("参数错误");
        }
        ew.eq("business_document_id",inputParam.getMainId());
        ew.orderByDesc("create_time");
        Page<BusinessOrder> result = this.page(new Page<BusinessOrder>(
                inputParam.getPage(),
                inputParam.getSize()),ew);
        Map<String, Object> map = new HashMap<String, Object>();
        List<BusinessOrder> rows=result.getRecords();
        for (int i = 0; i < rows.size(); i++) {
            BusinessOrder temp=rows.get(i);
//            //关联的订单信息
//            BusinessDocument document=businessDocumentService.getById(temp.getBusinessDocumentId());
//            temp.setBusinessDocument(document);
//            if (document!=null){//订单本身的合同与客户信息
//                Contract contract=contractService.getById(document.getContractId());
//                document.setContract(contract);
//                Comsumer comsumer=comsumerService.getById(document.getCustomerId());
//                document.setComsumer(comsumer);
//            }
            //车队信息
            CarFleet carFleet=carFleetService.getById(temp.getCarfleetId());
            temp.setCarFleet(carFleet);
            //特殊处理，原本的区域不使用，改成读取字典数据
//            Region startRegion=regionService.getById(temp.getStartPlace());
//            Region endRegion=regionService.getById(temp.getEndPlace());
            Region startRegion = typeDicService.formatRegion(temp.getStartPlace());
            Region endRegion = typeDicService.formatRegion(temp.getEndPlace());
            temp.setStartRegion(startRegion);
            temp.setEndRegion(endRegion);
        }
        map.put("rows", rows);
        map.put("total",result.getTotal());
        map.put("code", 1);
        return map;
    }
}
